<template>
  <div class="container">
    <h2>日志统计页面</h2>

    <!-- 显示加载中状态 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 登录日志统计 -->
    <div v-if="loginLogChartData">
      <h3>登录日志统计</h3>
      <canvas id="loginLogChart" style="height: 400px; width: 100%;"></canvas>
    </div>

    <!-- 操作日志统计 -->
    <div v-if="operationLogChartData">
      <h3>操作日志统计</h3>
      <canvas id="operationLogChart" style="height: 400px; width: 100%;"></canvas>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginLogChartData: null, // 登录日志数据
      operationLogChartData: null, // 操作日志数据
      loading: true, // 加载状态
    };

  },
  mounted() {
    this.fetchLogsData(); // 获取日志数据
  },
  methods: {
    // 获取数据
    async fetchLogsData() {
      try {
        // 查询登录日志数据
        const loginResponse = await fetch('http://192.168.231.31:8007/query/loginlogs');
        const loginLogs = await loginResponse.json();
        console.log("Login Logs:", loginLogs);  // 调试日志

        // 查询操作日志数据
        const operateResponse = await fetch('http://192.168.231.31:8007/query/operatelogs');
        const operateLogs = await operateResponse.json();

        // 处理并绘制图表
        this.loginLogChartData = this.processLoginLogs(loginLogs);
        this.operationLogChartData = this.processOperateLogs(operateLogs);

        // 绘制图表
        this.drawBarChart('loginLogChart', this.loginLogChartData);
        this.drawPieChart('operationLogChart', this.operationLogChartData);

        this.loading = false; // 加载完成
      } catch (error) {
        console.error('Error fetching logs data:', error);
      }
    },

    // 处理登录日志数据
    processLoginLogs(logs) {
      const userCounts = {};

      logs.forEach(log => {
        const user = log.username;
        userCounts[user] = (userCounts[user] || 0) + 1;
      });

      return {
        labels: Object.keys(userCounts),
        data: Object.values(userCounts),
      };
    },

    // 处理操作日志数据
    processOperateLogs(logs) {
      const operationCounts = {};

      logs.forEach(log => {
        const operation = log.username;
        operationCounts[operation] = (operationCounts[operation] || 0) + 1;
      });

      return {
        labels: Object.keys(operationCounts),
        data: Object.values(operationCounts),
      };
    },

    // 绘制柱状图
    drawBarChart(canvasId, chartData) {
      const ctx = document.getElementById(canvasId).getContext('2d');
      const { labels, data } = chartData;
      const barWidth = 40;
      const padding = 10;
      const maxData = Math.max(...data);

      const canvasWidth = ctx.canvas.width;
      const canvasHeight = ctx.canvas.height;
      const xInterval = (canvasWidth - padding * 2) / data.length;

      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      ctx.fillStyle = '#4BC0C0';

      data.forEach((dataPoint, index) => {
        const x = padding + index * xInterval;
        const y = canvasHeight - (dataPoint / maxData) * (canvasHeight - 50);
        const height = (dataPoint / maxData) * (canvasHeight - 50);
        ctx.fillRect(x, y, barWidth, height);
      });

      // 绘制x轴标签
      ctx.fillStyle = '#000';
      labels.forEach((label, index) => {
        const x = padding + index * xInterval + barWidth / 2;
        const y = canvasHeight - 10;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(label, x, y);
      });
    },

    // 绘制饼图
    drawPieChart(canvasId, chartData) {
      const ctx = document.getElementById(canvasId).getContext('2d');
      const { labels, data } = chartData;
      const canvasWidth = ctx.canvas.width;
      const canvasHeight = ctx.canvas.height;
      const radius = Math.min(canvasWidth, canvasHeight) / 2 - 10;
      const total = data.reduce((sum, value) => sum + value, 0);

      let currentAngle = -Math.PI / 2;

      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      ctx.translate(canvasWidth / 2, canvasHeight / 2); // 移动到圆心

      data.forEach((dataPoint, index) => {
        const sliceAngle = (dataPoint / total) * 2 * Math.PI;
        const color = this.getRandomColor();

        ctx.beginPath();
        ctx.arc(0, 0, radius, currentAngle, currentAngle + sliceAngle);
        ctx.lineTo(0, 0);
        ctx.fillStyle = color;
        ctx.fill();

        currentAngle += sliceAngle;
      });

      // 绘制标签
      ctx.fillStyle = '#000';
      let angleOffset = -Math.PI / 2;
      labels.forEach((label, index) => {
        const sliceAngle = (data[index] / total) * 2 * Math.PI;
        const midAngle = angleOffset + sliceAngle / 2;
        const x = radius * 0.6 * Math.cos(midAngle);
        const y = radius * 0.6 * Math.sin(midAngle);
        ctx.fillText(label, x, y);
        angleOffset += sliceAngle;
      });
    },

    // 随机生成颜色
    getRandomColor() {
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return `rgb(${r},${g},${b})`;
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  font-size: 28px;
}

.loading {
  text-align: center;
  font-size: 18px;
  color: #888;
}

canvas {
  margin-top: 20px;
}
</style>
